package com.xoa.plugin.ct;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.work.WorkMapper;
import com.xoa.global.proxy.TriggerSubject;
import com.xoa.model.nccloud.*;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.service.nccloud.*;
import com.xoa.util.DateUtil;
import com.xoa.util.ToJson;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 新增人员内部调动表单
 *
 */
@Service
public class CTPsnInnerStapplyPushTrigger {

    /*
    接口工具
     */
    @Autowired
    private INCCloudService nccloudService;

    //表数据
    private TriggerPlugIn tri = null;
    @Autowired
    INCCInterFaceLogService logService;

    @Autowired
    INCCPsndocService psndocService;

    @Autowired
    private WorkMapper workMapper;
    //人员对象
    private NccPsninfo nccPsninfo=null;
    @Autowired
    NccHrorgService nccHrorgService;
    @Autowired
    NccPsnclVService nccPsnclVService;
    @Autowired
    NccHrdeptService nccHrdeptService;
    //NCC 视图操作类
    @Autowired
    INCCViewService viewService;

    @Autowired
    NccPostseriesVService nccPostseriesVService;
@Autowired
NccPostVService nccPostVService;

    public ToJson doRun(TriggerPlugIn tri)throws Exception {


        this.tri = tri;
        //当前表单id
        String run_id = tri.getRunId();
        //表id
        String tableName = tri.getFlowId();
        String reqeustBody=null;
        ToJson toJson=new ToJson();
        try {

            //====1、判断是否为新增人员调动办理表单
            if (StringUtils.isNotBlank(run_id) && tableName.equals("292")) {



                    //=====2、请求nc接口保存获取主键
                    // 封装NC接口表所需json数据
                    reqeustBody = onversioncDto(tri.getModify(), run_id);
                    // 请求发送保存
                    String result = nccloudService.sendApi(nccloudService.psnStapplyUrl, reqeustBody);
                    //转换json对象
                    JSONObject rsjson = JSON.parseObject(result);
                    //判断请求是否错误
                    if (rsjson.getIntValue("code") == 1) {



                        //=====4、提交动作接口
                        // 接口调用成功 -- 取NC单据主键 pk_hi_stapply 存到记录行中
                        String pk = rsjson.getJSONObject("data").getString("pk_hi_stapply");
                        String billtype = rsjson.getJSONObject("data").getString("pk_billtype");

                        //保存单据主键和类型
                        this.saveBills(pk,billtype,run_id);

                        //请求发送保存json日志保存
                        this.saveLog(pk,reqeustBody,"城投个人内部调动300runid:"+run_id+"提交人员保存true",result,"1");

                        // 提交NC单据动作
                        //{"pk":"1001ZZ100000002R2LFJ","billType":"6115","checkNote":"","approveResult":"Y","action":"APPROVE"}
                        JSONObject[] jsonObjectRs = this.billsAction(pk,billtype,"","","SAVE");
                        //单据保存动作是否错误
                        if (jsonObjectRs[1].getIntValue("code") == 1) {


                            //请求发送动作json日志保存
                            this.saveLog(pk,jsonObjectRs[0].toJSONString(),"城投个人内部调动300runid:"+run_id+"提交人员保存动作true",jsonObjectRs[1].toJSONString(),"1");
                            toJson.setFlag(0);
                        } else {
                            //请求发送动作json日志保存
                            this.saveLog(pk,jsonObjectRs[0].toJSONString(),"城投个人内部调动300runid:"+run_id+"提交人员保存动作false",jsonObjectRs[1].toJSONString(),"0");
                            toJson.setFlag(1);
                            toJson.setMsg(jsonObjectRs[1].getString("message"));

                        }
                    } else {
                        //请求发送保存json日志保存
                        this.saveLog("",reqeustBody,"城投个人内部调动300runid:"+run_id+"提交人员保存false",result,"0");
                        toJson.setFlag(1);
                        toJson.setMsg(rsjson.getString("message"));

                    }
                }

        } catch (Exception e) {
            e.printStackTrace();
            //请求发送保存json日志保存
            this.saveLog("","","城投个人内部调动300runid:"+run_id+"false",e.getMessage(),"0");
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());

            }
        return toJson;

    }

    /**
     * 表单数据拼接json
     *
     * @param formdata
     * @param runId
     * @return
     * @throws Exception
     */

    public String onversioncDto(String formdata, String runId) throws Exception {
        nccPsninfo = new NccPsninfo();
        //将表单数据json数组解析List<Map<String, Object>>
        List<Map<String, Object>> data = JSONArray.parseObject(formdata, List.class);
        JSONObject jsonObject = new JSONObject();

        //保存部门名称
        String[] deptName=null;

        for (Map<String, Object> datum : data) {
            switch (datum.get("key").toString()) {
                case "DATA_3"://姓  名
                    break;
                case "DATA_143"://性别
                    break;
                case "DATA_7"://入职时间
                    break;
                case "DATA_39"://人员编号

                    //根据工号查询人员信息
                    nccPsninfo.setCode(datum.get("value").toString());
                    List<NccPsninfo> psninfoList = psndocService.selectPsn(nccPsninfo);

                    if (psninfoList.size() == 0 || null == psninfoList) {
                        throw new RuntimeException("根据人员编号查询不到人员信息！");
                    } else {
                        nccPsninfo = psninfoList.get(0);

                    }
                    jsonObject.put("pk_psndoc", nccPsninfo.getCode()); //人员
                    Map<String,Object> mapPostseriesV=new HashMap<>();
                    if (jsonObject.getString("pk_psndoc").equals("") || null == jsonObject.getString("pk_psndoc")) {
                        throw new RuntimeException("接口的pk_psndoc字段为空！");
                    }


                    jsonObject.put("newpk_org", nccPsninfo.getPkOrgCode()); //新组织
                    jsonObject.put("pk_hi_org",nccPsninfo.getPkOrgCode()); //新人员信息组织


                    break;
                case "DATA_47"://异动类别


                    NccTrnstypeV nccTrnstypeV=new NccTrnstypeV();
                    nccTrnstypeV.setTrnstypename("调动");
                    nccTrnstypeV.setTrnsevent("3");
                    List<NccTrnstypeV> nccTrnstypeVS = viewService.selectTrnstype(nccTrnstypeV);
                    if(null!=nccTrnstypeVS&&nccTrnstypeVS.size()!=0){
                        jsonObject.put("pk_trnstype", nccTrnstypeVS.get(0).getTrnstypecode()); //调配类型
                    }else {
                        throw new RuntimeException(nccTrnstypeV.getTrnstypename()+"查询不到编码！");
                    }
                    break;
                case "DATA_11"://异动时间
                    jsonObject.put("effectdate", datum.get("value")); //生效日期
                    break;

                case "DATA_161"://原部门
                    break;
                case "DATA_175"://新部门
                    deptName = datum.get("value").toString().split("_");
                    break;

                case "DATA_160"://原岗位
                    break;

                case "DATA_187"://新岗位
                    String[] newpk_postseries=datum.get("value").toString().split("_");
                    jsonObject.put("newpk_post",newpk_postseries[0]); //新岗位  f


                    Map<String,Object> map=new HashMap<>();
                    map.put("pkGroup","0001A210000000000GQS");
                    List<NccPostseriesV> nccPostseriesVListByMap = nccPostseriesVService.getNccPostseriesVListByMap(map);
                    if(null==nccPostseriesVListByMap||nccPostseriesVListByMap.size()==0){
                        throw new RuntimeException(map.get("pkGroup").toString()+"查询不到编码！");
                    }

                    //新岗位序列
                        jsonObject.put("newpk_postseries",nccPostseriesVListByMap.get(0).getPostseriescode()); //新岗位序列  f

                    break;


                case "DATA_166"://原组织
                    /*String[] DATA_33Split = datum.get("value").toString().split("_");

                    //设置参数
                    Map<String, Object> mapParam = new HashedMap<>();
                    mapParam.put("name", DATA_33Split[0]);

                    //获取组织集合
                    List<NccHrorg> nccHrorgListByMap = nccHrorgService.getNccHrorgListByMap(mapParam);
                    if (null == nccHrorgListByMap || nccHrorgListByMap.size() == 0) {
                        throw new RuntimeException("获取组织集合无！");
                    }
                    jsonObject.put("newpk_org", nccHrorgListByMap.get(0).getCode()); //新组织
                    jsonObject.put("pk_hi_org", nccHrorgListByMap.get(0).getCode()); //新人员信息组织*/
                    break;
            }
        }



                //获取部门编号

                //====2、根据组织pk查出部门
                //设置参数
                Map<String,Object> mapParam=new HashMap<>();
                mapParam=new HashedMap<>();
                mapParam.put("pkOrg", nccPsninfo.getPkOrg());

                //获取部门集合
                List<NccHrdept> nccHrdeptListByMap = nccHrdeptService.getNccHrdeptListByMap(mapParam);
                if(null==nccHrdeptListByMap||nccHrdeptListByMap.size()==0){
                    throw  new RuntimeException("没有pk_org:"+mapParam.get("pk_org")+"相关部门数据！");
                }else {
                    for(NccHrdept nccHrdept:nccHrdeptListByMap){
                        if(nccHrdept.getName().equals(deptName[0])){
                            jsonObject.put("newpk_dept",nccHrdept.getCode()); //新部门
                            mapParam=new HashedMap<>();
                            mapParam.put("pkDept", nccHrdept.getPkDept());
                            break;
                        }
                    }
                    if(null==jsonObject.getString("newpk_dept")||jsonObject.getString("newpk_dept").equals("")){
                        throw  new RuntimeException("新部门编码为空！");
                    }
                }




        jsonObject.put("apply_date",DateUtil.format(tri.getSendTime(), "yyyy-MM-dd")); //申请日期
        String[] dateArry = jsonObject.getString("apply_date").split("-");
        jsonObject.put("bill_code", "CTNBDD" + dateArry[0] + "" + dateArry[1] + "" + runId); //申请单编号
        jsonObject.put("ifaddblack","N"); //加入黑名单
        jsonObject.put("ifaddpsnchg","N"); //内部调配增加流动记录
        jsonObject.put("stapply_mode","1"); //调配方式
        jsonObject.put("newpk_psncl","0101");//新人员类别0101
        jsonObject.put("ifsynwork","Y"); //同步工作履历
        jsonObject.put("isdisablepsn","N"); //停用离职人员
        jsonObject.put("isend","N"); //终止
        jsonObject.put("ishrssbill","N"); //是否自助
        jsonObject.put("isneedfile","N"); //附件必传
        jsonObject.put("isrelease","N"); //解除
        jsonObject.put("newpoststat","N"); //新是否在岗  f
        jsonObject.put("trial_flag","N"); //试用
        jsonObject.put("newpk_job",""); //新职务  f
        jsonObject.put("newpk_job_type",""); //新职务类型 f
        jsonObject.put("newdeposemode",""); //新免职方式  f
        jsonObject.put("pk_billtype","6113"); //单据类型  m
        jsonObject.put("pk_group","0001A210000000000GQS"); //集团
        jsonObject.put("pk_hi_stapply",""); //调配申请单主键
        jsonObject.put("pk_org",nccPsninfo.getPkOrgCode()); //人事组织
        jsonObject.put("memo",""); //离职说明  f
        jsonObject.put("newmemo",""); //新备注  f
        jsonObject.put("ifendpart","N"); //结束兼职
        jsonObject.put("sreason", "02");//异动原因
        jsonObject.put("assgid","1"); //人员任职id  m
        jsonObject.put("workflow_state","-1"); //workflow_state  m
        jsonObject.put("newjobglbdef3", ""); //新行政级别  f
        jsonObject.put("billmaker","NCCOA"); //制单人tri.getUsers().getUserName()

        if(null==nccPsninfo.getJobglbdef2()){
            jsonObject.put("newjobglbdef2",""); //任现职时间	  f
        }else {
            jsonObject.put("newjobglbdef2",nccPsninfo.getJobglbdef2()); //任现职时间	  f
        }
        if(null==nccPsninfo.getJobglbdef4()){
            jsonObject.put("newjobglbdef4", ""); //任现职级时间  f
        }else {
            jsonObject.put("newjobglbdef4", nccPsninfo.getJobglbdef4()); //任现职级时间  f
        }





        String danJuJson = "{\"billhead\":" + jsonObject.toJSONString() + "}";

        return danJuJson;
    }


    /**
     * 日志保存
     * @param pk
     * @param reqeustBody
     * @param name
     * @param result
     * @throws Exception
     */
    private void saveLog(String pk,String reqeustBody,String name,String result,String state)throws Exception{
        NCCInterfaceLog ncclog = new NCCInterfaceLog();
        ncclog.setBusinessNo(pk);
        ncclog.setContent(reqeustBody);
        ncclog.setName(name);
        ncclog.setResult(result);
        ncclog.setState(state);
        ncclog.setDisposeState("0");
        logService.save(ncclog);
    }


    /**
     * 单据动作
     * @param bills
     * @return
     * @throws Exception
     */
    public JSONObject[] billsAction(String... bills)throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pk",bills[0]);//单据主键
        jsonObject.put("billType",bills[1]);//单据类型编码
        jsonObject.put("checkNote",bills[2]);//批语
        jsonObject.put("approveResult",bills[3]);//审批结果
        jsonObject.put("action",bills[4]);//单据动作名称
        //请求发送动作
        String rs = nccloudService.sendApi(nccloudService.billactionUrl, jsonObject.toJSONString());

        return new JSONObject[]{jsonObject,JSON.parseObject(rs)};
    }

    /**
     * 保存单据信息
     * @param pk
     * @param billsType
     * @param run_id
     * @throws Exception
     */
    public void saveBills(String pk,String billsType,String run_id)throws Exception{
        // 保存主键的动作
        List<String> key = new ArrayList();
        key.add("pk_hi_stapply='"+pk+"'");
        key.add("billsType='"+billsType+"'");
        Map<String, Object> param = new HashMap();
        param.put("tableName", "flow_data_292");
        param.put("keys", key);
        param.put("runId", run_id);
        workMapper.update(param);
    }

}

